package cn.gene.timeyan.ums.webapi.ums.controller;

import cn.gene.timeyan.common.restful.JsonResult;
import cn.gene.timeyan.pojo.ums.dto.*;
import cn.gene.timeyan.pojo.ums.model.Set;
import cn.gene.timeyan.pojo.ums.model.User;
import cn.gene.timeyan.ums.service.IUserService;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import sun.font.FontDesignMetrics;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.Hashtable;
import java.util.List;

/**
 * 用户基本（常用）信息表 前端控制器*
 *
 * @author LWG
 * @date 2022/7/23 10:30
 * @since 1.0.0@gene.cn
 */
@Slf4j
@RestController
@RequestMapping("/ums/user")
@Api(tags = "用户信息功能")
public class UserController {
    private static final String QR_CODE_IMAGE_PATH = "D:/二维码.png";
    @Autowired
    IUserService userService;

    @ApiOperation("设置二维码保存属性")
    private static void generateQRCodeImage(String text, int width, int height, String filePath) throws WriterException, IOException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();

        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);//H最高容错等级
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");

        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height,hints);

        Path path = FileSystems.getDefault().getPath(filePath);

        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);

    }
    //图片转为字符串
    public static String getImageStr(String filePath) {
        InputStream inputStream = null;
        byte[] data = null;
        try {
            inputStream = new FileInputStream(filePath);
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 加密
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);
    }

    //字符串转为图片
    public static boolean generateImage(String imgStr, String filename) {
        if (imgStr == null) {
            return false;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // 解密
            byte[] b = decoder.decodeBuffer(imgStr);
            // 处理数据
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            OutputStream out = new FileOutputStream("D://" + filename);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }
    //添加水印
    public static void addText(String srcPath, String content) throws IOException {
        //  读取原图片信息
        BufferedImage srcImage = ImageIO.read(new File(srcPath));
        int width = srcImage.getWidth();
        int height = srcImage.getHeight();

        //  创建画笔，设置绘图区域
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bufferedImage.createGraphics();
        g.drawImage(srcImage, 0, 0, width, height, null);
        //        g.drawImage(srcImage.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);

        g.setFont(new Font("宋体", Font.PLAIN, 32));
        g.setColor(Color.RED);

        //  计算文字长度
        int len = g.getFontMetrics(g.getFont()).charsWidth(content.toCharArray(), 0, content.length());
        FontDesignMetrics metrics = FontDesignMetrics.getMetrics(g.getFont());
        int len2 = metrics.stringWidth(content);
        System.out.println(len);
        System.out.println(len2);

        //  计算文字坐标
        int x = width - len - 10;
        int y = height - 20;
        //        int x = width - 2 * len;
        //        int y = height - 1 * len;

        g.drawString(content, x, y);

        g.dispose();

        //  输出文件
        FileOutputStream fos = new FileOutputStream("D:\\水印\\1.png");
        ImageIO.write(bufferedImage, "png", fos);
        fos.flush();
        fos.close();
    }
    @ApiOperation("图片转为字节流")
    private static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        // 设置每次读取缓存区大小
        byte[] buffer = new byte[1024 * 10];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }


    @ApiOperation("根据用户ID生成二维码")
    @GetMapping("/selectById")
    public String selectById(@Validated UserDetailPicDTO addDTO){
        String base64EncoderImg="";
        User user=userService.selectById(addDTO.getUserId());
        try {
            log.info(user.toString());
            String res="";
            String email=user.getEmail();res=res+"邮箱："+email;res+=" ";
            String phone=user.getPhone();res=res+"电话："+phone;res+=" ";
            Integer state=user.getUserState();
            String is_vip=user.getIsVip();
            if(state==1){
                res=res+"账号状态：异常";res+=" ";
            }else{
                res=res+"账号状态：正常";res+=" ";
            }
            if(is_vip.charAt(0)=='1'){
                res=res+"是否是vip:否";res+=" ";
            }else{
                res=res+"是否是vip:是";res+=" ";
            }
            log.info(res);
            generateQRCodeImage(res, 350, 350, QR_CODE_IMAGE_PATH);
            InputStream inputStream=new FileInputStream("d:/二维码.png");
            byte faceImage[]=readInputStream(inputStream);
            base64EncoderImg = Base64.encodeBase64String(faceImage);
        } catch (WriterException e) {
            System.out.println("Could not generate QR Code, WriterException :: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("Could not generate QR Code, IOException :: " + e.getMessage());
        }catch (Exception e){
        }
        return base64EncoderImg;
    }

    @ApiOperation("后台用户管理")
    @GetMapping("/SuperSelectById")
    public JsonResult<User> SuperSelectById(Long userId){
        return JsonResult.ok(userService.SuperSelectById(userId));
    }

    @ApiOperation("根据用户旧密码实现更改密码")
    @PostMapping("/updatePassword")
    public String updatePasswordById(@Validated ChangePasswordDTO changePassword){
        String oldPassword1=userService.SuperSelectById(changePassword.getUserId()).getPassword();
        log.info(changePassword.getOldPassword()+"----"+oldPassword1);
        if(changePassword.getOldPassword().equals(oldPassword1)){
            userService.updatePasswordById(changePassword.getUserId(),changePassword.getNewPassword());
            return "修改成功";
        }
        return "原密码不正确，请重新修改";
    }

    @ApiOperation("更改用户头像")
    @GetMapping("/updateHeader")
    public String updateHeader(@Validated UpdateHeaderDTO headerDTO){
        userService.updateHeader(headerDTO.getUserId(),headerDTO.getImgURL());
        return "修改成功";
    }

    @ApiOperation("用户调研功能")
    @GetMapping("/collectMark")
    public String collectMark(@Validated UserMarkDTO userDTO){
        userService.collectMark(userDTO.getUserId(),userDTO.getMarkLevel());
        int level= Integer.valueOf(String.valueOf(userDTO.getMarkLevel()));
        switch (level){
            case 1:
                return "非常不满意";
            case 2:
                return "不满意";
            case 3:
                return "一般";
            case 4:
                return "较好";
            default:
                return "非常满意";
        }
    }

    @ApiOperation("设置图片上传是否加水印")
    @GetMapping("/isWatermark")
    public String isWatermark(@Validated UpdateHeaderDTO userDTO) throws IOException {
        Set set=userService.isWatermark(userDTO.getUserId());
        String isMark=set.getWatermark();
        if (isMark.equals("1")) {
            System.out.println(userDTO.getImgURL());
            generateImage(userDTO.getImgURL(),"原图片.png");
            addText("D:\\原图片.png","时光源");
            String resURL=getImageStr("D:\\水印\\1.png");
            return resURL;
        }
        return userDTO.getImgURL();
    }

    /**  dj
     * 添加用户
     * @return
     */
    @PostMapping("/add-new")
    @ApiOperation("添加用户基本信息")
    public JsonResult<Long> addNew(@Validated @RequestBody UserRegistryDTO userRegistryDTO) {
        Long userId = userService.addnew(userRegistryDTO,userRegistryDTO.getVerifCode());
        return JsonResult.ok(userId);
    }

    /**  lwg
     * 返回所有用户
     * @return
     */
    @ApiOperation(value="获取所有用户")
    @GetMapping("/user-list")
//    @PreAuthorize("hasRole('ROLE_user')")
    public JsonResult<List> list(){
        return JsonResult.ok(userService.list());
    }

}

